<template>
  <div>
    <!-- 页面头部：标题+操作按钮 -->
    <div class="page-header">
      <el-row :gutter="20" align="middle">
        <el-col>
          <h2>测试数据管理</h2>
        </el-col>
        <el-col :align="`right`">
          <el-button type="primary" size="small" @click="openAddDialog">
            <el-icon><Plus /></el-icon> 新增数据
          </el-button>
          <el-button type="default" size="small" style="margin-left: 10px">
            <el-icon><Upload /></el-icon> 批量导入
          </el-button>
          <el-button type="default" size="small" style="margin-left: 10px" @click="exportData">
            <el-icon><Download /></el-icon> 批量导出
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索与筛选 -->
    <el-card shadow="hover" style="margin-top: 15px">
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="数据名称">
          <el-input v-model="searchForm.name" placeholder="请输入数据名称" size="small" />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" size="small">
            <el-option label="全部类型" value="" />
            <el-option label="接口参数模板" value="api_param" />
            <el-option label="UI测试账号" value="ui_account" />
            <el-option label="环境配置" value="env_config" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="date"
            placeholder="选择创建日期"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="getDataList">搜索</el-button>
          <el-button type="default" size="small" style="margin-left: 10px" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表 -->
    <el-card shadow="hover" style="margin-top: 15px">
      <el-table
        v-loading="loading"
        :data="dataList"
        border
        stripe
        size="small"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="数据ID" width="80" align="center" />
        <el-table-column prop="name" label="数据名称" align="center" />
        <el-table-column label="数据类型" align="center" width="140">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center" width="200">
          <template #default="scope">{{ scope.row.description || '-' }}</template>
        </el-table-column>
        <el-table-column label="数据内容" align="center" min-width="200">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="previewData(scope.row.data_content)"
            >
              查看内容
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" align="center" width="180" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button type="text" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="text" size="small" text-color="#f56c6c" @click="deleteData(scope.row.id)">删除</el-button>
            <el-button type="text" size="small" text-color="#4361ee" @click="copyData(scope.row.id)">复制</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑数据弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑测试数据' : '新增测试数据'"
      width="600px"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRules"
        label-width="120px"
      >
        <el-form-item label="数据名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入数据名称（如：登录接口参数）" />
        </el-form-item>
        <el-form-item label="数据类型" prop="type">
          <el-select v-model="dataForm.type" placeholder="请选择数据类型">
            <el-option label="接口参数模板" value="api_param" />
            <el-option label="UI测试账号" value="ui_account" />
            <el-option label="环境配置" value="env_config" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="dataForm.description"
            type="textarea"
            rows="2"
            placeholder="请输入数据描述（可选）"
          />
        </el-form-item>
        <el-form-item label="数据内容" prop="data_content">
          <el-input
            v-model="dataForm.data_content"
            type="textarea"
            rows="6"
            placeholder="请输入数据内容（JSON格式，如 {&quot;username&quot;: &quot;test&quot;}）"
          />
          <div class="param-tip" v-if="dataForm.type === 'api_param'">
            <span class="text-gray-500 text-sm">
              提示：接口参数模板需为JSON格式，可在接口用例中直接引用
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据内容预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="数据内容预览"
      width="600px"
    >
      <pre class="data-preview">{{ previewContent }}</pre>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElTag, ElIcon } from 'element-plus'
import { Plus, Upload, Download, CopyDocument } from '@element-plus/icons-vue'
import request from '@/api/request'

// 数据列表
const dataList = ref([])
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const loading = ref(false)
const selectedRows = ref([]) // 选中的数据（用于批量操作）

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  createTime: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dataFormRef = ref(null)
const dataForm = reactive({
  id: '',
  name: '',
  type: '',
  description: '',
  data_content: ''
})

// 预览弹窗
const previewVisible = ref(false)
const previewContent = ref('')

// 表单验证规则
const dataRules = reactive({
  name: [{ required: true, message: '请输入数据名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据类型', trigger: 'change' }],
  data_content: [{ required: true, message: '请输入数据内容', trigger: 'blur' }]
})

// 页面挂载时加载数据
onMounted(() => {
  getDataList()
})

// 1. 获取数据列表（对接Django接口）
const getDataList = async () => {
  loading.value = true
  try {
    // 处理日期参数
    const createTime = searchForm.createTime ? formatDate(searchForm.createTime) : ''
    const res = await request.get('/api/test-data/list/', {
      params: {
        page: page.value,
        limit: limit.value,
        name: searchForm.name,
        type: searchForm.type,
        create_time: createTime
      }
    })
    dataList.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('获取数据列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 2. 打开新增弹窗
const openAddDialog = () => {
  isEdit.value = false
  resetDataForm()
  dialogVisible.value = true
}

// 3. 打开编辑弹窗
const openEditDialog = (row) => {
  isEdit.value = true
  // 深拷贝数据到表单
  Object.assign(dataForm, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

// 4. 提交表单（新增/编辑）
const submitForm = async () => {
  const valid = await dataFormRef.value.validate()
  if (!valid) return

  try {
    // 验证数据内容是否为JSON格式（非必填，但建议接口参数模板强制验证）
    if (dataForm.type === 'api_param') {
      JSON.parse(dataForm.data_content)
    }
  } catch (error) {
    ElMessage.error('数据内容格式错误，请输入合法的JSON')
    return
  }

  try {
    if (isEdit.value) {
      // 编辑数据
      await request.put(`/api/test-data/${dataForm.id}/`, dataForm)
      ElMessage.success('编辑成功')
    } else {
      // 新增数据
      await request.post('/api/test-data/', dataForm)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getDataList() // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.msg || error.message))
  }
}

// 5. 删除数据
const deleteData = (id) => {
  ElMessageBox.confirm(
    '确认删除该测试数据吗？删除后不可恢复',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/api/test-data/${id}/`)
      ElMessage.success('删除成功')
      getDataList()
    } catch (error) {
      ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 6. 复制数据（快速创建副本）
const copyData = async (id) => {
  try {
    const res = await request.post(`/api/test-data/${id}/copy/`)
    ElMessage.success('复制成功，已创建新数据')
    getDataList()
  } catch (error) {
    ElMessage.error('复制失败：' + (error.response?.data?.msg || error.message))
  }
}

// 7. 预览数据内容
const previewData = (content) => {
  try {
    // 格式化JSON显示（更易读）
    previewContent.value = JSON.stringify(JSON.parse(content), null, 2)
  } catch (error) {
    previewContent.value = content // 非JSON格式直接显示
  }
  previewVisible.value = true
}

// 8. 导出数据
const exportData = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先勾选要导出的数据')
    return
  }
  const ids = selectedRows.value.map(row => row.id).join(',')
  try {
    const res = await request.get('/api/test-data/export/', {
      params: { ids },
      responseType: 'blob'
    })
    // 触发下载
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = `测试数据_${new Date().getTime()}.json`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + (error.response?.data?.msg || error.message))
  }
}

// 辅助函数：重置表单
const resetDataForm = () => {
  dataForm.id = ''
  dataForm.name = ''
  dataForm.type = ''
  dataForm.description = ''
  dataForm.data_content = ''
  if (dataFormRef.value) {
    dataFormRef.value.resetFields()
  }
}

// 辅助函数：重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.createTime = ''
  getDataList()
}

// 辅助函数：获取数据类型显示名
const getTypeName = (type) => {
  const typeMap = {
    'api_param': '接口参数模板',
    'ui_account': 'UI测试账号',
    'env_config': '环境配置'
  }
  return typeMap[type] || '未知类型'
}

// 辅助函数：获取数据类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    'api_param': 'primary',
    'ui_account': 'success',
    'env_config': 'info'
  }
  return typeMap[type] || 'default'
}

// 分页相关
const handleSizeChange = (val) => {
  limit.value = val
  page.value = 1
  getDataList()
}
const handleCurrentChange = (val) => {
  page.value = val
  getDataList()
}

// 选择数据变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  try {
    const d = new Date(date)
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
  } catch (error) {
    return ''
  }
}
</script>

<style scoped lang="scss">
.page-header {
  padding: 20px;
  h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
}

.search-form {
  padding: 15px 0;
}

.param-tip {
  margin-top: 8px;
  .text-gray-500 {
    color: #909399;
    font-size: 12px;
  }
}

.data-preview {
  width: 100%;
  white-space: pre-wrap;
  word-break: break-all;
  color: #333;
  font-family: 'Consolas', 'Monaco', monospace;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>